(ns nodemem
  (:require [cljs.nodejs :as nodejs]))

(def fs (nodejs/require "fs"))
(def http (nodejs/require "http"))

(def state (atom {}))

(defn parse-mem [s]
   (loop [res {}
          in (take 4 (.split s "\n"))]
      (if-let [l (first in)]
         (let [a (.split l #"\b")]
            (recur (assoc res (keyword (first a)) (nth a 2)) (next in)))
         (swap! state (fn [_] res)))))

(defn load-mem [path]
   (.readFile fs path "utf8"
      (fn [err data] (if err (prn "Error:" err) (parse-mem data)))))

(defn request-handler [req res]
   (let [mem (pr-str @state)] 
      (.writeHead res 200 "Content-Type: text/plain\nAccess-Control-Allow-Origin: *")
      (.end res mem)))

(defn ^:export reload []
   (prn "reloading data")
   (load-mem "/proc/meminfo")
   (js* "setTimeout(nodemem.reload, 3000)"))

(defn -main [& paths] 
  (reload)
  (.listen (.createServer http request-handler) 8080 "127.0.0.1")
  (prn "Server running at http://127.0.0.1:8080"))

(set! *main-cli-fn* -main)
